<!--
 * @Date: 2024-11-27 09:25:20
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2025-02-18 10:46:20
 * @Description: 面板Node
-->
<template>
  <component
    ref="compRef"
    :is="component"
    :layout="grid"
    :design="design"
    :schema="grid.schema"
    @mounted="registerPanelRef"
  >
  </component>
</template>

<script setup>
import { onBeforeMount, onBeforeUnmount, ref, shallowRef, watch } from 'vue';
import { pluginManager } from '@hp/utils/pluginManager.js'

const props = defineProps({
  grid: { type: Object },
  design: { type: Boolean, default: true }
})

const compRef = ref(null)
const component = shallowRef(null)
const initComponent = async () => {
  const { grid } = props
  const cmp = pluginManager.getPanelComp(grid.type)
  // 内部不存在组件
  if (!cmp) {
    console.error(`组件${grid.type}未注册`)
    return
  }

  // 如果数据项为函数，则判定为懒加载组件
  if (typeof cmp === 'function') {
    const res = await cmp()
    component.value = res.default ?? res
  } else {
    // 否则为预加载组件
    component.value = cmp
  }
}

/**
 * 注册组件的Ref
 */
const registerPanelRef = () => {
  setTimeout(() => { pluginManager.registerPanelsRef(props.grid.i, compRef.value) }, 300)
}

onBeforeUnmount(() => {
  pluginManager.removePanelRef(props.grid.i)
})

watch(
  () => props.grid.type,
  () => {
    initComponent()
  },
  { deep: true, immediate: true }
)

</script>

<style lang="scss" scoped>

</style>